import {View, Text, Image, Button, Input} from '@tarojs/components'
import React, {useState, useEffect} from 'react'
import "./homeIndex.less"
import Taro from "@tarojs/taro"
import {AtModal, AtModalHeader, AtModalContent, AtModalAction} from "taro-ui"
import {Swiper, SwiperItem} from '@tarojs/components'
import goodImg from '../../../img/tabbarIcon/1.png'
import store from "../../../store";
import http from '../../../service/api'

const Home = () => {
    const [swiperData, setSwiperData] = useState([
        {
            descMessage: "",
            grade: "",
            id: "",
            img: "",
            name: "",
            price: "",
            sum: "",
            text: ""
        },
    ])
    // useEffect(() => {
    //     getTuijian(15)
    // }, [])
    //获取的轮播数据
    //第一个弹框
    const getTuijian = (userId) => {
        Taro.request({
            url: http.api3 + "/customerMain/getRecommendGoods",
            method: "post",
            header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
                userId
            },
            success(res) {
                // console.log(res.data)
                // console.log(res.data.information)
                setSwiperData(res.data.data)
                setSwiperGood(res.data.data[0])
            },
            fail(err) {
                console.log("失败了")
            }
        })
    }
    const getNew = () => {
        Taro.request({
            url: http.api3 + "/customerMain/newGoodsTop",
            method: "post",
            header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            success(res) {
                console.log("new")
                console.log(res)
                // console.log(res.data.information)
                let newData = res.data.data.splice(0, 2)
                setNewGoods(newData)
                store.setNewData(res.data.data)
            },
            fail(err) {
                console.log("失败了")
            }
        })
    }
    const getHot = () => {
        Taro.request({
            url: http.api3 + "/customerMain/getHotSaleGoods",
            method: "post",
            header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            
            success(res) {
                console.log("hot")
                console.log(res)
                // console.log(res.data.information)
                setHotData(res.data.data)
                store.setSelectNoneData(res.data.data)
            },
            fail(err) {
                console.log("失败了")
            }
        })
    }
    const [isopen, setIsopen] = useState(true)
    //电话弹框
    const [isopen1, setIsopen1] = useState(false)
    //拒绝弹框
    const [isopen2, setIsopen2] = useState(false)
    
    //热销data
    const [hotData, setHotData] = useState([
        {
            id: "",
            name: "",
            grade: "",
            text: "",
            sum: "",
            price: "",
            img: ""
        }
    ])
    //轮播数据前的数据展示
    const [swiperGood, setSwiperGood] = useState(
        {
            id: "",
            name: "",
            grade: "",
            text: "",
            sum: "",
            price: "",
            img: ""
        }
    )
    //新品data
    const [newGoods, setNewGoods] = useState([
        {
            id: "",
            name: "",
            grade: "",
            text: "",
            sum: "",
            price: "",
            img: ""
        }
        ]
    )
    const phoneInput = (e) => {
        // setPhone(e.detail.value)
        store.setUserPhone(e.detail.value)
    }
    const search = () => {
       
         Taro.request({
            url: http.api4 + "/portalIndex/selectGoods",
            method: "get",
            header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
                uid: store.userInformation.id
            },
            success(res) {
                // console.log("hot")
                console.log(res)
                // console.log(res.data.information)
                store.setHotGoods(res.data.hotGoods)
                store.setHistoryGoods(res.data.history)
                Taro.navigateTo({
                    url: "../homeSelect/homeSelect"
                })
            },
            fail(err) {
                console.log("失败了")
            }
        })
    }
    const swiperChange = (current) => {
        let data = {};
        // console.log(swiperData[current].title)
        data.name = swiperData[current].name;
        data.text = swiperData[current].text;
        data.grade = swiperData[current].grade;
        data.sum = swiperData[current].sum;
        data.price = swiperData[current].price;
        data.id = swiperData[current].id
        setSwiperGood(data)
    }
    //获取更多新品
    const getMore = () => {
        Taro.navigateTo({
            url: "../homeNew/homeNew"
        })
    }
    // 商品详情跳转，需要传递商品id
    const goodData = (item) => {
        store.setDataId(item.id)
        store.setSid(item.bid)
            Taro.navigateTo({
                url: "../../details/details"
            })
    }
    //第一个弹框
    const login1 = () => {
        // console.log("登录");
        setIsopen(false)
        Taro.getUserProfile({
            lang: 'zh_CN',
            desc: "获取你的昵称、头像、地区及性别",
            success: response => {
                const wxUserInfo = response.userInfo;
                // console.log('getUserProfile', wxUserInfo);
                setIsopen1(true)
            store.setUserData(wxUserInfo)
            },
            fail: () => {
                //拒绝授权
                setIsopen2(true)
                console.error("您拒绝了请求");
                return;
            }
        })
    }
    const cancel1 = () => {
        setIsopen1(false)
        setIsopen2(true)
    }
    const setToken = (token) => {
        Taro.request({
            url: http.api2 + "/user/validateLoginStatus",
            method: "post",
            header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
                token
            },
            success(res) {
                // console.log(res.data.information)
                store.setUserInformation(res.data.information)
                // console.log(res.data.information)
                getTuijian(res.data.information.id)
                getHot()
                getNew()
            },
            fail(err) {
                console.log("失败了")
            }
        })
    }
    const login2 = () => {
        setIsopen1(false)
        Taro.request({
            url: http.api1 + "/portalUser/login",
            method: "post",
            header: {
                'content-type': 'application/json' // 默认值
            },
            data: {
                phone: store.userPhone,
                name: store.userData.nickName
            },
            success(res) {
                store.setToken(res.data.token)
                let token = res.data.token
                setToken(token)
            },
            fail(err) {
                console.log("失败了")
            }
        })
    }
    
    return (
        <View>
            <View className={"home"}>
                <View className="homeTitle">
                    <Text className="titleText"> {store.userData.nickName}，你好！</Text>
                    <View className="littleText">
                        <Text>今天为您推荐4款新品哦~</Text>
                    </View>
                    <View className="titleLeft" onClick={search}>
                        <View className='at-icon at-icon-search'/>
                    </View>
                </View>
            </View>
            <View className="lunbo">
                <Swiper
                    className='test-h'
                    indicatorColor='#999'
                    indicatorActiveColor='#333'
                    circular
                    current={0}
                    autoplay
                    onChange={(e) => {
                        swiperChange(e.detail.current)
                    }}>
                    {swiperData.map((item) => {
                        return (
                            <SwiperItem onClick={() => {
                                goodData(item)
                            }}>
                                <View className='demo-text'>
                                    <Image src={item.img} className="goodImg"/>
                                </View>
                            </SwiperItem>
                        )
                    })}
                
                </Swiper>
                <View className="swiperGood">
                    <View className="swiperLeft">
                        <View className="goodTitle">{swiperGood.name}</View>
                        <View className="goodText">{swiperGood.text}</View>
                        <View style={{fontSize: "11px"}}>已售{swiperGood.sum}件</View>
                    </View>
                    <View className="swiperRight">
                        <View className="goodGrade">
                            <View className='at-icon at-icon-star'>
                                <Text className="text">{swiperGood.grade}</Text>
                            </View>
                        </View>
                        <View>￥{swiperGood.price}</View>
                    </View>
                </View>
            </View>
            <View className="newTop">
                <View className="newTitle">
                    <View className="name">新品Top10</View>
                    <View className="more" onClick={getMore}>查看更多
                        <View className='at-icon at-icon-chevron-right'/>
                    </View>
                </View>
                <View className="newGoods">
                        {newGoods.map((item) => {
                                return (
                                    <View className="good" onClick={() => {
                                        goodData(item)
                                    }}>
                                        <Image src={item.img} className="img" lazyLoad={true}/>
                                        <View style={{fontSize: "15px"}}>{item.name}</View>
                                        <View style={{fontSize: "15px"}}>￥{item.price}</View>
                                    </View>
                                )
                            })}
                </View>
            </View>
            <View className="hot">
                <View className="hotTitle">热销</View>
                <View className="hotGoods">
                    {hotData.map((item) => {
                        return (
                            <View className="hotGood" onClick={() => {
                                goodData(item)
                            }}>
                                <Image src={item.img} className="img" lazyLoad={true}/>
                                <View>{item.name}</View>
                                <View>￥{item.price}</View>
                            </View>
                        )
                    })}
                </View>
            </View>
            <AtModal
                isOpened={isopen}
                closeOnClickOverlay={false}
            >
                <AtModalContent>
                    <View className={"loginText"}>小程序需要获取您的信息哦</View>
                </AtModalContent>
                <AtModalAction>
                    <Button onClick={login1}>确定</Button>
                </AtModalAction>
            </AtModal>
            <AtModal
                isOpened={isopen1}
                closeOnClickOverlay={false}
            >
                <AtModalContent>
                    <View style={{fontSize: "15px", textAlign: "center"}}>请输入您的手机号</View>
                    <Input className="numInput" type="text" placeholder="请输入手机号" onInput={phoneInput} maxlength='11'/>
                </AtModalContent>
                <AtModalAction>
                    <Button onClick={cancel1}>取消</Button>
                    <Button onClick={login2}>确定</Button>
                </AtModalAction>
            </AtModal>
            <AtModal
                isOpened={isopen2}
                closeOnClickOverlay={false}
            >
                <AtModalContent>
                    <View className={"loginText"}>您拒绝了请求哦</View>
                </AtModalContent>
            </AtModal>
        </View>
    )
}
export default Home